import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lib_module_manager/module_manager/module.dart';
import 'package:lib_module_manager/module_manager/widgets/page_widget.dart';

typedef CreatePage = Page? Function({
  required Module module,
  String? id,
  Map<String, dynamic>? params,
});

abstract class Page {
  final Key _moduleKey = const ValueKey("module");
  final Expando<Module> _module = Expando("module");
  Module get module => _module[_moduleKey]!;

  late MethodChannel channel;

  String type;
  String? id;

  Map<String, dynamic>? _params;

  Future<Map<String, dynamic>?> get params async {
    if (_params != null) {
      return _params;
    }

    Map? params = await channel.invokeMethod<Map>('getPageParams');
    return params == null ? null : Map<String, dynamic>.from(params);
  }

  PageWidget? get pageWidget;

  void setCompletion({int delta = 1, dynamic param}) {
    channel.invokeMethod<bool>('setPageCompletionParam', {
      'delta': delta,
      'param': param,
    });
  }

  Page({
    required Module module,
    required this.type,
    this.id,
    Map<String, dynamic>? params,
  }) {
    _module[_moduleKey] = module;

    _params = params;

    channel = const MethodChannel('page-lifecycle');
  }
}
